<template>
	<div class="form">
		<h6>请提供您的保单收件信息，我们将快递给您</h6>
		<div class="row">
			<label>收件人</label>
			<input v-if="!hasSubmit" type="text" placeholder="请输入收件人姓名" v-model="receiveName" />
			<p v-else>{{receiveName}}</p>
		</div>
		<div class="row">
			<label>联系电话</label>
			<input v-if="!hasSubmit" type="tel" placeholder="请输入联系电话" v-model="receivePhone" />
			<p v-else>{{receivePhone}}</p>
		</div>
		<div class="row">
			<label>保单收件地址</label>
			<textarea v-if="!hasSubmit" placeholder="请输入保单收件地址" v-model="receiveAddr"></textarea>
			<p v-else>{{receiveAddr}}</p>
		</div>
		<div class="row">
			<button v-if="!hasSubmit" class="submit" :class={disabled:disabled} @click="onSubmitClick">提交</button>
			<button v-else class="submit disabled">已提交</button>
		</div>
	</div>
</template>

<script>
import toast from '@/components/toast'

export default {
	props: {
		id: {},
		name: {},
		phone: {},
		address: {},
		submited: {
			type: Boolean
		},
		onSubmit: {
			type: Function,
			required: true
		}
	},
	data() {
		return {
			receiveName: '',
			receivePhone: '',
			receiveAddr: '',
			hasSubmit: false,
			disabled: true,
		}
	},
	created() {
		this.receiveName = this.name || ''
		this.receivePhone = this.phone || ''
		this.receiveAddr = this.address || ''
		this.hasSubmit = this.submited

		this.checkForm()
	},
	methods: {
		setDisabled() {
			this.hasSubmit = true
		},
		onSubmitClick() {
			this.receiveName = this.receiveName.trim()
			this.receivePhone = this.receivePhone.trim()
			this.receiveAddr = this.receiveAddr.trim()

			if (this.receiveName === '') {
				toast.show('收件人姓名不能为空')
			} else if (this.receivePhone === '') {
				toast.show('联系电话不能为空')
			} else if(!(/^1[34578]\d{9}$/).test(this.receivePhone)){
                toast.show('请输入正确的联系电话')
            } else if (this.receiveAddr === '') {
            	toast.show('保单收件地址不能为空')
            } else {
            	this.onSubmit({
            		id: this.id,
            		receiveName: this.receiveName,
            		receivePhone: this.receivePhone,
            		receiveAddr: this.receiveAddr,
            	}, this.setDisabled)
            }
		},
		checkForm() {
			this.receiveName = this.receiveName.trim()
			this.receivePhone = this.receivePhone.trim()
			this.receiveAddr = this.receiveAddr.trim()

			this.disabled = true

			if (this.receiveName === '') {
				return false
			} else if (this.receivePhone === '') {
				return false
			} else if(!(/^1[34578]\d{9}$/).test(this.receivePhone)){
                return false
            } else if (this.receiveAddr === '') {
            	return false
            }

			this.disabled = false
		}
	},
	watch: {
		receivePhone(v) {
			this.receivePhone = v.substr(0,11)
			this.checkForm()
		},
		receiveName() {
			this.checkForm()
		},
		receiveAddr() {
			this.checkForm()
		}
	}
}
</script>

<style scoped lang="scss">
	@import './style'
</style>